﻿using DevExpress.Persistent.BaseImpl;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;

namespace EasyXaf.EntityDesigner.BusinessObjects.Entities.Associations;

/// <summary>
/// 关系
/// </summary>
public partial class Association : BaseObject
{
    private partial bool GetIsValid()
    {
        if (Parent != Entity && Child != Entity)
        {
            return false;
        }
        return true;
    }

    private partial string GetParentPropertyName()
    {
        return ParentProperty?.Name ?? Name.Split('-').Skip(1).FirstOrDefault();
    }

    private partial string GetChildPropertyName()
    {
        return ChildProperty?.Name ?? Name.Split('-').FirstOrDefault();
    }

    private partial IList<Entity> GetEntityDataSource()
    {
        return Entity?.DomainModel.AllEntities;
    }

    private partial IList<EntityProperty> GetParentPropertyDataSource()
    {
        return Parent?.Properties;
    }

    private partial IList<EntityProperty> GetChildPropertyDataSource()
    {
        return Child?.Properties;
    }

    protected override void OnSaving()
    {
        base.OnSaving();

        if (ChildProperty != null)
        {
            var childPropertyType = ChildProperty.PropertyType;
            if (ParentProperty != null)
            {
                var parentPropertyType = ParentProperty.PropertyType;
                if (parentPropertyType == PropertyType.Entity && childPropertyType == PropertyType.Entity)
                {
                    AssociationType = AssociationType.OneToOne;
                }
                else if (parentPropertyType == PropertyType.EntityCollection && childPropertyType == PropertyType.EntityCollection)
                {
                    AssociationType = AssociationType.ManyToMany;
                }
                else
                {
                    AssociationType = AssociationType.OneToMany;
                }
            }
            else if (childPropertyType == PropertyType.EntityCollection)
            {
                AssociationType = AssociationType.ManyToMany;
            }
        }
        else if (ParentProperty != null && ParentProperty.PropertyType == PropertyType.Entity)
        {
            AssociationType = AssociationType.OneToOne;
        }
    }
}
